#include "CChangeTreeParentCommand.h"
#include "CUserInterface.h"
#include "CLevelEditor.h"
#include "ISceneManager.h"
#include "ISceneNode.h"
#include "IGUITreeCtrl.h"

extern CGlobals* g;
extern CUserInterface* ui;
extern CLevelEditor* editor;

CChangeTreeParentCommand::CChangeTreeParentCommand (int id, int oldParentId, int newParentId)
{
	m_id = id;
	m_oldParentId = oldParentId;
	m_newParentId = newParentId;
	setDescription(L"change parent");
}

void CChangeTreeParentCommand::redo ()
{
	TreeNode* node = ui->m_sceneGraphTree->FindNode(m_id);
	TreeNode* newParentNode = ui->m_sceneGraphTree->FindNode(m_newParentId);
	ui->m_sceneGraphTree->ChangeParent(node, newParentNode);
	ui->m_sceneGraphTree->SetSelected(node);

	matrix4 matAbsTransform = node->SceneObject->m_SceneNode->getAbsoluteTransformation();
	ISceneNode *pSceneParent = NULL;
	if (newParentNode)
	{
		pSceneParent = newParentNode->SceneObject->m_SceneNode;
		if (newParentNode->SceneObject->m_UserData->getAttributeAsString("!GameType") == "Geometry" &&
			node->SceneObject->m_UserData->getAttributeAsString("!GameType") != "NavMesh")
		{
			pSceneParent = editor->GetRoomRefNode(newParentNode->SceneObject->m_SceneNode);
		}
	}
	else
	{
		pSceneParent = g->sceneManager->getRootSceneNode();
	}
	pSceneParent->addChild(node->SceneObject->m_SceneNode);
	matrix4 matParentAbsTransform = pSceneParent->getAbsoluteTransformation();
	matParentAbsTransform.makeInverse();
	node->SceneObject->m_SceneNode->setRelativeTransformation(matParentAbsTransform * matAbsTransform);
}

void CChangeTreeParentCommand::undo ()
{
	TreeNode* node = ui->m_sceneGraphTree->FindNode(m_id);
	TreeNode* oldParentNode = ui->m_sceneGraphTree->FindNode(m_oldParentId);
	ui->m_sceneGraphTree->ChangeParent(node, oldParentNode);
	ui->m_sceneGraphTree->SetSelected(node);
	
	matrix4 matAbsTransform = node->SceneObject->m_SceneNode->getAbsoluteTransformation();
	ISceneNode *pSceneParent = NULL;
	if (oldParentNode)
	{
		pSceneParent = oldParentNode->SceneObject->m_SceneNode;
		if (oldParentNode->SceneObject->m_UserData->getAttributeAsString("!GameType") == "Geometry" &&
			node->SceneObject->m_UserData->getAttributeAsString("!GameType") != "NavMesh")
		{
			pSceneParent = editor->GetRoomRefNode(oldParentNode->SceneObject->m_SceneNode);
		}
	}
	else
	{
		pSceneParent = g->sceneManager->getRootSceneNode();
	}
	
	pSceneParent->addChild(node->SceneObject->m_SceneNode);
	matrix4 matParentAbsTransform = pSceneParent->getAbsoluteTransformation();
	matParentAbsTransform.makeInverse();
	node->SceneObject->m_SceneNode->setRelativeTransformation(matParentAbsTransform * matAbsTransform);
}
